added samples
[windows-sources.git] / sdk / samples / all in on code / Visual Studio 2008 / ManagedAggregator / ManagedAggregator.cs
blob4364a1c41031a5cb1d4363ff9158561e4e13710f
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Runtime.InteropServices;
5 using System.Runtime.Remoting;
7 namespace ManagedHelpers
9 // This interface will be implemented by the outer object in the
10 // aggregation - that is, by the shim.
11 [ComImport]
12 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
13 [Guid("7B70C487-B741-4973-B915-B812A91BDF63")]
14 internal interface IComAggregator
16 void SetInnerPointer(IntPtr pUnkInner);
19 // This interface is implemented by the managed aggregator - the single
20 // method is a wrapper around Marshal.CreateAggregatedObject, which can be
21 // called from unmanaged code (that is, called from the shim).
22 [ComImport]
23 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
24 [Guid("142A261B-1550-4849-B109-715AA4629A14")]
25 internal interface IManagedAggregator
27 void CreateAggregatedInstance(
28 string assemblyName, string typeName, IComAggregator outerObject);
31 // The unmanaged shim will instantiate this object in order to call
32 // through to Marshal.CreateAggregatedObject.
33 [ClassInterface(ClassInterfaceType.None)]
34 [ProgId("ManagedHelpers.ManagedAggregator")]
35 internal class ManagedAggregator : IManagedAggregator
37 public void CreateAggregatedInstance(
38 string assemblyName, string typeName, IComAggregator outerObject)
40 IntPtr pOuter = IntPtr.Zero;
41 IntPtr pInner = IntPtr.Zero;
43 try
45 // We use Marshal.CreateAggregatedObject to create a CCW where
46 // the inner object (the target managed add-in) is aggregated
47 // with the supplied outer object (the shim).
48 pOuter = Marshal.GetIUnknownForObject(outerObject);
49 object innerObject =
50 AppDomain.CurrentDomain.CreateInstanceAndUnwrap(
51 assemblyName, typeName);
52 pInner = Marshal.CreateAggregatedObject(pOuter, innerObject);
54 // Make sure the shim has a pointer to the add-in.
55 outerObject.SetInnerPointer(pInner);
57 finally
59 if (pOuter != IntPtr.Zero)
61 Marshal.Release(pOuter);
63 if (pInner != IntPtr.Zero)
65 Marshal.Release(pInner);